﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infratructure.Interfares;
using B.S.BaseData.Read.Api.Application.Command;
using B.S.BaseData.Read.Api.Dtos;
using MediatR;

namespace B.S.BaseData.Read.Api.Application.CommandHander
{
    public class UserLoginCommandHander : IRequestHandler<UserLoginCommand, ApiResult<UserLoginDto>>
    {
        private readonly IMapper mapper;
        private readonly ILogger<UserLoginCommandHander> logger;
        private readonly IBaseRequsitory<User> userRequsitory;
        private readonly IBaseRequsitory<Role> roleResitort;
        private readonly IBaseRequsitory<UserRole> userroleResitort;

        public UserLoginCommandHander(IMapper mapper, ILogger<UserLoginCommandHander> logger, IBaseRequsitory<User> userRequsitory, IBaseRequsitory<Role> roleResitort, IBaseRequsitory<UserRole> userroleResitort)
        {
            this.mapper = mapper;
            this.logger = logger;
            this.userRequsitory = userRequsitory;
            this.roleResitort = roleResitort;
            this.userroleResitort = userroleResitort;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<UserLoginDto>> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            ApiResult<UserLoginDto> result = new ApiResult<UserLoginDto>();

            var list = userRequsitory.GetAllAsync().Where(x => x.UserName == request.UserName).FirstOrDefault();

            if (list==null)
            {
                result.Code = ApiEnum.用户名不存在;
                result.Msg = ApiEnum.用户名不存在.ToString();
            }
            else
            {
                if (list.Password!=request.Password)
                {
                    result.Code = ApiEnum.密码错误;
                    result.Msg = ApiEnum.密码错误.ToString();
                }
                else
                {
                    result.Code = ApiEnum.登录成功;
                    result.Msg = ApiEnum.登录成功.ToString();
                    result.Data = mapper.Map<UserLoginDto>(list);
                }
            }

            return Task.FromResult(result);
        }
    }
}
